﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Quickuse.Logging
{
    /// <summary>
    /// LoggerScope
    /// </summary>
    internal class LoggerScope
    {
        private readonly string _categoryName;
        private readonly object _state;

        private static AsyncLocal<LoggerScope> _value = new AsyncLocal<LoggerScope>();

        /// <summary>
        /// FileLogScope
        /// </summary>
        /// <param name="categoryName">categoryName</param>
        /// <param name="state">state</param>
        internal LoggerScope(string categoryName, object state)
        {
            _categoryName = categoryName;
            _state = state;
        }

        /// <summary>
        /// 
        /// </summary>
        public LoggerScope Parent { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        public static LoggerScope Current
        {
            set
            {
                _value.Value = value;
            }
            get
            {
                return _value.Value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="categoryName"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public static IDisposable Push(string categoryName, object state)
        {
            var temp = Current;
            Current = new LoggerScope(categoryName, state);
            Current.Parent = temp;

            return new DisposableScope();
        }

        /// <summary>
        /// 
        /// </summary>
        private class DisposableScope : IDisposable
        {
            public void Dispose()
            {
                Current = Current.Parent;
            }
        }
    }
}
